package com.google.memoryofaplace.controller;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.memoryofaplace.General;

public class Delete extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BlobstoreService blobstoreService = BlobstoreServiceFactory
			.getBlobstoreService();

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		// redirect to post
		try {
			doPost(req, res);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setCharacterEncoding("UTF-8");
		res.setContentType("application/json;charset=UTF-8");
		JSONObject jReturn = new JSONObject();

		try {
			BlobKey blobKey = new BlobKey(req.getParameter("key"));
			{
				blobstoreService.delete(blobKey);
				jReturn.put("status", General.OK);
				jReturn.put("date", General.formatDate(new Date()));
			}
		} catch (Exception e) {
			jReturn = new JSONObject();
			jReturn = General.returnError(e.getMessage());
		}

		res.getWriter().print(jReturn.toString());
	}
}